package com.atguigu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.entity.DictListener;
import com.atguigu.mapper.DictMapper;
import com.atguigu.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    private DictMapper dictMapper;
    //不同的缓存可以放在不同的命名空间下
    //value后是命名空间
    @Cacheable(value = "dict", key = "'cache_'+#id")
    @Override
    public List<Dict> findChildData(Long id) {
        //创建字典条件
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        List<Dict> dictList = baseMapper.selectList(queryWrapper);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            boolean isChild = this.isChildren(dictId);
            dict.setHasChildren(isChild);
        }
        return dictList;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        //设置响应头
        response.setContentType("application/vnd.ms-excel");//设置响应内容格式
        response.setCharacterEncoding("utf-8");
        String fileName = null;//中文乱码
        try {
            fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");//附件形式下载
            //查找所有数据字典
            List<Dict> dictList = baseMapper.selectList(null);
            //泛型转换
            List<DictEeVo> dictVoList = new ArrayList<>();
            for (Dict dict : dictList) {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict, dictEeVo);
                dictVoList.add(dictEeVo);
            }
            //调用写的方法
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Autowired
    private DictListener dictListener;
    //清除所有dict缓存
    @CacheEvict(value = "dict",allEntries = true)   //该注解标识的方法体每次都会被执行
    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, dictListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        //如果没传递parentDictCode，就只根据value去查询
      if(StringUtils.isEmpty(parentDictCode)){
          QueryWrapper<Dict> queryWrapper=new QueryWrapper();
          queryWrapper.eq("value",value);
          Dict dict = dictMapper.selectOne(queryWrapper);
          return  dict.getName();
      }else {
          //根据parentDictCode来查询
          Dict parent = this.getDictByDictCode(parentDictCode);
          Long id = parent.getId();
          QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
          queryWrapper.eq("parent_id",id);
          queryWrapper.eq("value",value);
          Dict dict = baseMapper.selectOne(queryWrapper);
          return  dict.getName();
      }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = this.getDictByDictCode(dictCode);
        //查询子节点
        List<Dict> list = this.findChildData(dict.getId());
        return list;
    }

    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> queryWrapper =new QueryWrapper();
        queryWrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);
        return  dict;
    }

    //判断id下面是否有子节
    private boolean isChildren(Long dictId) {
        //创建条件
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id", dictId);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }


}
